package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.Exception.LeaseException;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void getCode(String phone) {
        //1. 检查手机号码是否为空
        /*StringUtils.hasText:适用于需要综合判断字符串是否为有效内容（如验证用户输入是否为空或纯空格）*/
        if (!StringUtils.hasText(phone)) throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        //2. 检查Redis中是否已经存在该手机号码的key
        String rediskey = RedisConstant.APP_LOGIN_PREFIX + phone;
        if (redisTemplate.hasKey(rediskey)) {
            //若存在，则检查其存在的时间
            /*获取此redis资源将要过期的时间*/
            Long expire = redisTemplate.getExpire(rediskey, TimeUnit.SECONDS);
            //若存在时间不足一分钟，响应发送过于频繁
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < 60)
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //3.发送短信，并将验证码存入Redis
        String code = VerifyCodeUtil.getCode(6);
        smsService.sendCode(phone, code);
        redisTemplate.opsForValue().set(rediskey, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }

    @Override
    public String getJwt(LoginVo loginVo) {
        /*判断手机号或者验证码是否为空*/
        if (loginVo.getCode().isEmpty()) throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        if (loginVo.getPhone().isEmpty()) throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);

        /*判断验证码是否过期和错误*/
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = (String)redisTemplate.opsForValue().get(key);
        if (code == null) throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        if (!code.equals(loginVo.getCode())) throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);

        /*判断是否是新账户*/
        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getPhone, loginVo.getPhone()));

        if (userInfo == null) {
            /*注册*/
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setNickname("用户-" + loginVo.getPhone().substring(7));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        } else {
            /*是否禁用*/
            if (userInfo.getStatus() == BaseStatus.DISABLE)
                throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        /*返回jwt*/
        return JwtUtil.generateJwt(userInfo.getPhone(), userInfo.getId());
    }

    @Override
    public UserInfoVo getInfoById(Long userId) {
        UserInfo byId = userInfoService.getById(userId);
        return new UserInfoVo(byId.getNickname(), byId.getAvatarUrl());
    }
}
